package com.linh.bus.html;

import java.util.ArrayList;
import java.util.List;

import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.CssSelectorNodeFilter;
import org.htmlparser.util.NodeList;
import org.w3c.dom.Document;

import com.linhngua.code.xml.XmlProcessor;

public class BusHtmlParserImpl implements BusHtmlParser {

	XmlProcessor xmlProcessor;

	public BusHtmlParserImpl(XmlProcessor xmlProcessor) {
		super();
		this.xmlProcessor = xmlProcessor;
	}

	public List<LocationSearchResult> parse(String html)
			throws BusHtmlParserException {

		return doParse(html);
	}

	List<LocationSearchResult> doParse(String html)
			throws BusHtmlParserException {
		List<LocationSearchResult> results = new ArrayList<LocationSearchResult>();

		try {
			Parser htmlParser = new Parser(html);
			NodeFilter nodeFilter = new CssSelectorNodeFilter("span.place a");
			NodeList nodeList = htmlParser.parse(nodeFilter);
			for (int i = 0; i < nodeList.size(); i++) {
				String locationHtml = nodeList.elementAt(i).toHtml();
				Document doc = xmlProcessor.getXmlDocument(locationHtml);
				String locationUrl = xmlProcessor.getNode("//@href", doc)
						.getTextContent();
				String description = xmlProcessor.getNode("//a", doc)
						.getTextContent();
				LocationSearchResult l = new LocationSearchResult(locationUrl,
						description);
				results.add(l);
			}

			return results;

		} catch (Exception ex) {
			throw new BusHtmlParserException(ex);
		}
	}

	public String parseMoreLink(String html) throws BusHtmlParserException {
		try {
			Parser parser = new Parser(html);
			NodeFilter nodeFilter = new CssSelectorNodeFilter("a#moreLink");
			NodeList nodeList = parser.extractAllNodesThatMatch(nodeFilter);
			if (nodeList.size() > 0) {
				String linkHtml = nodeList.elementAt(0).toHtml();
				Document doc = xmlProcessor.getXmlDocument(linkHtml);
				return xmlProcessor.getNode("//@href", doc).getTextContent();
			} else {
				return null;
			}

		} catch (Exception ex) {
			throw new BusHtmlParserException(ex);
		}

	}

}
